﻿using AutoMapper;
using Dapper;
using MediatR;
using Microsoft.AspNetCore.Http.HttpResults;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.W.realize;
using System.Data;

namespace MyMES.Writer.API.Application.CommendHandlers.W.realize
{
    public class AddArrivalmanagementCommandHanders : IRequestHandler<AddArrivalmanagementCommands, APIResult<Arrivalmanagement>>
    {
        private readonly IBaseRepository<Arrivalmanagement> baseRepository;
        private readonly IMapper mapper;
        public DatabaseContext db;

        public AddArrivalmanagementCommandHanders(IBaseRepository<Arrivalmanagement> baseRepository, IMapper mapper, DatabaseContext db)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 添加到票信息
        /// </summary>
        /// <param name="request">添加</param>
        /// <param name="cancellationToken">2025年4月16日11:55:32</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Arrivalmanagement>> Handle(AddArrivalmanagementCommands request, CancellationToken cancellationToken)
        {
            APIResult<Arrivalmanagement> result = new APIResult<Arrivalmanagement>();

            using (var connection = db.Connection)
            {
                if (connection.State!=ConnectionState.Open)
                {
                    connection.Open();
                }
                request.Createid ??=new List<int> ();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var Arrival = mapper.Map<Arrivalmanagement>(request);

                        var sql= "insert into Arrivalmanagement (ArrivalNumber, ArrivalName, Arrivaltype, ArrivalTime, Drawer, Invoicenumber, Remark, IsDelete) values (@ArrivalNumber, @ArrivalName, @Arrivaltype, @ArrivalTime, @Drawer, @Invoicenumber, @Remark, @IsDelete); SELECT LAST_INSERT_ID();";
                        var ArrivalId = await connection.ExecuteScalarAsync<int>(
                            sql,
                            Arrival,
                            transaction);

                        if(ArrivalId > 0)
                        {
                            if (request.Createid.Any())
                            {
                                const string sql1 = $"insert into ArrivalSales (Aid, SalesId) values (@Aid, @SalesId)";
                                foreach (var SalesId in request.Createid)
                                {
                                    await connection.ExecuteAsync(
                                        sql1,
                                        new
                                        {
                                            Aid = ArrivalId,
                                            SalesId = SalesId,
                                        }, transaction);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("插入 Arrivalmanagement 表失败，无法获取有效的 ArrivalId");
                        }

                        transaction.Commit();
                        var newdata = await connection.QueryFirstOrDefaultAsync<Arrivalmanagement>("select * from Arrivalmanagement where Aid = @Aid", new { Aid = ArrivalId });

                        result.Code = APIEnum.添加成功;
                        result.Msg = $"到票成功，销售订单数：{request.Createid.Count}";
                        result.data = newdata;

                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception("添加到票信息失败，事务已回滚", ex);
                    }
                }
            }

            return result;
        }
    }
}
